<template>
  <Modal
    v-model="modelIsOpen"
    width="900"
    height="600px"
    mask
    :closable="false"
  >
    <template #footer>
      <div class="modal-buttons">
        <Button
          type="primary"
          size="default"
          @click="downloadTmpl"
          :loading="btnLoading"
          >下载模板</Button
        >
        <div>
          <Button size="default" @click="cancel" :loading="btnLoading"
            >取消</Button
          >
          <Button
            type="primary"
            size="default"
            :loading="btnLoading"
            @click="ok"
            >确定</Button
          >
          <!-- <Poptip class="ml-10" placement="bottom-start" transfer>
            <Button
              type="primary"
              size="default"
              :loading="btnLoading"
              @click="ok"
              >确定</Button
            >
            <template #content>
              <Progress :percent="downPercent" :status="downStatus" />
            </template>
          </Poptip> -->
        </div>
      </div>
    </template>

    <Space direction="vertical" size="default" type="flex">
      <zz-Label :text="title"></zz-Label>
      <div class="select-import-mode-box" v-if="showImportMode">
        <zz-Form ref="zzForm" title="请选择导入模式">
          <div class="select-import-mode">
            <RadioGroup
              v-model="importType"
              size="small"
              @on-change="changeImportMode"
            >
              <Radio label="1" :disabled="showMode !== 'fileSelect'"
                >存在时抛错</Radio
              >
              <Radio label="2" :disabled="showMode !== 'fileSelect'"
                >存在时替换</Radio
              >
              <Radio label="3" :disabled="showMode !== 'fileSelect'"
                >存在时跳过</Radio
              >
            </RadioGroup>
          </div>
        </zz-Form>
      </div>
    </Space>

    <Upload
      name="excelFile"
      multiple
      type="drag"
      :action="'api/' + uploadUrl + '/' + tmplId + '/' + importType"
      accept=".xlsx,.xls"
      :show-upload-list="false"
      :headers="getHeaders()"
      :max-size="10240"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
      :on-progress="onProgress"
      :on-error="onError"
      class="upload-component"
      v-if="showMode === 'fileSelect'"
    >
      <div style="padding: 20px 0">
        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
        <p>预导入：请点击或拖拽文件！</p>
      </div>
    </Upload>

    <div class="table-component" v-else>
      <Tabs v-model="tabName">
        <TabPane
          v-for="(item, key) in importData"
          :key="key"
          :label="item.sheetName"
          :name="key + ''"
        ></TabPane>
      </Tabs>
      <template v-for="(item, key) in importData" :key="key">
        <template v-if="key + '' === tabName">
          <zz-Table
            :data="item.dataList"
            :hasPage="false"
            ref="zzTable"
            :loading="loading"
            :size="'mini'"
          >
            <vxe-table-column
              type="seq"
              title="序号"
              minWidth="60"
            ></vxe-table-column>
            <vxe-table-column field="flagStatus" title="状态" minWidth="120">
              <template #default="{ row }">
                {{ row.errMsg ? '失败' : '成功' }}
              </template>
            </vxe-table-column>
            <vxe-table-column
              field="errMsg"
              title="失败原因"
              minWidth="120"
              v-if="showEr"
            ></vxe-table-column>
            <vxe-table-column
              v-for="(item2, key2) in item.col"
              :key="key2"
              :field="item2.field"
              :title="item2.title"
              min-width="120"
            ></vxe-table-column>
          </zz-Table>
        </template>
      </template>
    </div>
    <Progress
      v-if="downPercent !== 0 && downPercent !== 100"
      :percent="downPercent"
      :status="downStatus"
      :stroke-width="2"
    />
  </Modal>
</template>

<script>
import { saveAs } from 'file-saver'
export default {
  name: 'zzImport',
  emits: ['beforeSuccess', 'success'],
  props: {
    tmplId: {
      type: String,
      default: '',
      required: true,
    },

    uploadUrl: {
      type: String,
      default: '',
    },
    saveUrl: {
      type: String,
      default: '',
    },
    showImportMode: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
      default: '导入',
    },
    downFileName: {
      type: String,
      default: '下载模板',
    },
  },
  watch: {
    modelIsOpen: {
      async handler(newVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: false,
    },
  },
  data() {
    return {
      modelIsOpen: false,
      btnLoading: false,
      loading: false,
      showEr: false,
      importType: '1', // 导入模式
      showMode: 'fileSelect', // 展示文件选择框or预导入表格
      model: {},
      downPercent: 0,
      downStatus: null,
      tabName: '0',
      importData: [],
    }
  },
  methods: {
    init() {
      // this.getFakerImportData()
    },
    changeImportMode(val) {},

    async downloadTmpl() {
      this.btnLoading = true
      this.downPercent = 0
      this.downStatus = null

      // 进度条
      const downInterval = setInterval(() => {
        if (this.downPercent >= 90) {
          clearInterval(downInterval)
          return
        }
        this.downPercent += 10
      }, 500)

      try {
        const res = await this.$API.userManagement.user.importData.down(
          this.tmplId
        )
        if (res) {
          saveAs(
            new Blob([res], { type: 'application/vnd.ms-excel' }),
            this.downFileName + '.xlsx'
          )
          this.downPercent = 100
          this.btnLoading = false
          setTimeout(() => {
            clearInterval(downInterval)
          }, 500)
        } else {
          this.btnLoading = false
          this.downStatus = 'wrong'
          this.$Message.error('呕吼，有点问题，获取文件失败了')
        }
      } catch (e) {
        this.btnLoading = false
        this.downStatus = 'wrong'
        this.$Message.error('呕吼，有点问题，获取文件失败了')
      }
    },
    getHeaders() {
      // 设置Token登录信息
      let token = JSON.parse(this.$TOOL.session.get('token'))
      let userCode = JSON.parse(this.$TOOL.session.get('userInfo')).userCode
      return {
        AUTH_TOKEN: token,
        USER_CODE: userCode,
      }
    },
    beforeUpload() {},
    onSuccess(response) {
      if (response.code === '01') {
        this.importData = response.data
        // 按需重构
        this.importData.forEach((item) => {
          // 重新遍历列
          item.col = []
          for (const key in item.columnList) {
            item.col.push({
              field: key,
              title: item.columnList[key],
            })
          }
          // 添加遍历赋值错误字段
          item.dataList.forEach((item) => {
            item.errMsg = ''
          })
          // 搜集错误数据
          if (item.importExcelErrDTOList) {
            this.showEr = true
            item.importExcelErrDTOList.forEach((item2) => {
              item2.rowNums.forEach((item3) => {
                item.dataList[
                  item3 - 1
                ].errMsg += `第${item3}行${item2.columnTitle}${item2.errMsg}；`
              })
            })
          } else {
            this.showEr = false
          }
        })
        this.showMode = 'preImporData'
        // 文件上传成功时返回
        this.$emit('beforeSuccess', this.importData)
      }
    },
    onProgress() {},
    onError() {
      console.log('error')
    },
    async ok() {
      if (this.importData.length !== 0) {
        this.loading = true

        // 将预导入失败的行过滤掉
        for (let i = 0; i < this.importData.length; i++) {
          if (this.importData[i].importExcelErrDTOList) {
            let filterIndexs = this.importData[i].importExcelErrDTOList.map(
              (e) => e.rowNums[0] - 1
            )
            this.importData[i].dataList = this.importData[i].dataList.filter(
              (e, index) => !filterIndexs.includes(index)
            )
          }
        }

        try {
          const res = await this.$API.public.import.save.post(this.saveUrl, {
            dataList: this.importData,
            importType: this.importType,
            tmplId: this.tmplId,
          })
          if (res.code === '01') {
            this.$Message.success('导入成功')
            this.$emit('success', res)
            this.cancel()
          } else {
            this.$Message.error(res.message)
          }
        } catch (error) {
          // console.error(error)
        }

        this.loading = false
      } else {
        this.$Message.warning('请导入文件')
      }
    },
    cancel() {
      this.modelIsOpen = false
      this.reset()
    },
    reset() {
      this.model = {}
      this.importType = '1'
      this.showMode = 'fileSelect'
      this.downPercent = 0
      this.showEr = false
    },
    getFakerImportData() {
      this.importData = [
        {
          sheetName: 'Sheet 1',
          dataList: [
            {
              flagStatus: true,
              errMsg: '',
              field1: 'Value 1',
              field2: 'Value 2',
            },
            {
              flagStatus: false,
              errMsg: 'Error message',
              field1: 'Value 3',
              field2: 'Value 4',
            },
          ],
          col: [
            { field: 'field1', title: 'Field 1' },
            { field: 'field2', title: 'Field 2' },
          ],
        },
        {
          sheetName: 'Sheet 2',
          dataList: [
            {
              flagStatus: true,
              errMsg: '',
              field1: 'Value 1.1',
              field2: 'Value 2.2',
            },
            {
              flagStatus: false,
              errMsg: 'zzz',
              field1: 'Value 3',
              field2: 'Value 4',
            },
            {
              flagStatus: false,
              errMsg: 'zzz',
              field1: 'Value 3',
              field2: 'Value 4',
            },
            {
              flagStatus: false,
              errMsg: 'zzz',
              field1: 'Value 3',
              field2: 'Value 4',
            },
            {
              flagStatus: false,
              errMsg: 'zzz',
              field1: 'Value 3',
              field2: 'Value 4',
            },
            {
              flagStatus: false,
              errMsg: 'zzz',
              field1: 'Value 3',
              field2: 'Value 4',
            },
            {
              flagStatus: false,
              errMsg: 'zzz',
              field1: 'Value 3',
              field2: 'Value 4',
            },
            {
              flagStatus: false,
              errMsg: 'zzz',
              field1: 'Value 3',
              field2: 'Value 4',
            },
            {
              flagStatus: false,
              errMsg: 'zzz',
              field1: 'Value 3',
              field2: 'Value 4',
            },
          ],
          col: [
            { field: 'field1', title: 'Field 1' },
            { field: 'field2', title: 'Field 2' },
          ],
        },
      ]
    },
  },
}
</script>

<style lang="less" scoped>
.select-import-mode-box {
  margin-top: 5px;
}
.ivu-radio-wrapper {
  font-size: 12px;
}
.select-import-mode {
  margin-left: 10px;
}
:deep(.ivu-tabs-tab) {
  font-size: 12px;
}
.upload-component {
  margin-top: 10px;
}
.table-component {
  margin-top: 10px;
  margin-bottom: 20px;
  height: 200px;
}
.modal-buttons {
  display: flex;
  justify-content: space-between;
}
</style>
